<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';

import * as echarts from 'echarts';

const chartRef = ref<HTMLElement>();
let chartInstance: echarts.ECharts | null = null;

onMounted(() => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);

    const option = {
      title: {
        text: '皇族成员分布',
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}人 ({d}%)',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
      },
      series: [
        {
          name: '成员分布',
          type: 'pie',
          radius: '60%',
          data: [
            {
              value: 1,
              name: '第1代（太祖）',
              itemStyle: { color: '#faad14' },
            },
            {
              value: 8,
              name: '第2代（藩王）',
              itemStyle: { color: '#1890ff' },
            },
            { value: 3, name: '第3代', itemStyle: { color: '#52c41a' } },
            { value: 2, name: '第4代', itemStyle: { color: '#722ed1' } },
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
          label: {
            formatter: '{b}\n{c}人',
          },
        },
      ],
    };

    chartInstance.setOption(option);

    window.addEventListener('resize', handleResize);
  }
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  chartInstance?.dispose();
});

function handleResize() {
  chartInstance?.resize();
}
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 300px"></div>
</template>
